package com.example.demo.utils.photoUtils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class ImageResizerUI {

    public static void resizeImage(File inputFile, File outputFile, int width, int height) throws IOException {
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(inputFile);

        // 创建目标大小的图片
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 绘制拉伸后的图片
        Graphics2D g = resizedImage.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,  RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.drawImage(originalImage,  0, 0, width, height, null);
        g.dispose();

        // 获取输出格式
        String formatName = "jpg"; // 统一输出为JPG格式
        if (outputFile.getName().toLowerCase().endsWith(".png"))  {
            formatName = "png";
        }

        // 写入输出文件
        ImageIO.write(resizedImage,  formatName, outputFile);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()  -> new ImageResizerUIWithJFIFSupport().setVisible(true));
    }
}

class ImageResizerUIWithJFIFSupport extends JFrame {
    private JTextField inputDirField;
    private JTextField outputDirField;
    private JTextField widthField;
    private JTextField heightField;
    private JProgressBar progressBar;
    private JButton processBtn;
    private JCheckBox preserveFormatCheckBox;

    public ImageResizerUIWithJFIFSupport() {
        setTitle("批量图片处理工具 (支持JFIF)");
        setSize(550, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15,  15, 15, 15));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill  = GridBagConstraints.HORIZONTAL;
        gbc.insets  = new Insets(8, 8, 8, 8);

        // 输入目录选择
        gbc.gridx  = 0;
        gbc.gridy  = 0;
        mainPanel.add(new  JLabel("输入目录:"), gbc);

        gbc.gridx  = 1;
        gbc.weightx  = 1;
        inputDirField = new JTextField();
        JButton inputDirBtn = new JButton("浏览...");
        inputDirBtn.addActionListener(new  DirectoryChooser(inputDirField));
        JPanel inputDirPanel = new JPanel(new BorderLayout(5, 0));
        inputDirPanel.add(inputDirField,  BorderLayout.CENTER);
        inputDirPanel.add(inputDirBtn,  BorderLayout.EAST);
        mainPanel.add(inputDirPanel,  gbc);

        // 输出目录选择
        gbc.gridx  = 0;
        gbc.gridy  = 1;
        gbc.weightx  = 0;
        mainPanel.add(new  JLabel("输出目录:"), gbc);

        gbc.gridx  = 1;
        gbc.weightx  = 1;
        outputDirField = new JTextField();
        JButton outputDirBtn = new JButton("浏览...");
        outputDirBtn.addActionListener(new  DirectoryChooser(outputDirField));
        JPanel outputDirPanel = new JPanel(new BorderLayout(5, 0));
        outputDirPanel.add(outputDirField,  BorderLayout.CENTER);
        outputDirPanel.add(outputDirBtn,  BorderLayout.EAST);
        mainPanel.add(outputDirPanel,  gbc);

        // 分辨率设置
        gbc.gridx  = 0;
        gbc.gridy  = 2;
        gbc.weightx  = 0;
        mainPanel.add(new  JLabel("宽度(像素):"), gbc);

        gbc.gridx  = 1;
        widthField = new JTextField("2400");
        mainPanel.add(widthField,  gbc);

        gbc.gridx  = 0;
        gbc.gridy  = 3;
        mainPanel.add(new  JLabel("高度(像素):"), gbc);

        gbc.gridx  = 1;
        heightField = new JTextField("1800");
        mainPanel.add(heightField,  gbc);

        // 格式选项
        gbc.gridx  = 0;
        gbc.gridy  = 4;
        gbc.gridwidth  = 2;
        preserveFormatCheckBox = new JCheckBox("保持原始格式 (不勾选则统一转为JPG)");
        preserveFormatCheckBox.setSelected(false);
        mainPanel.add(preserveFormatCheckBox,  gbc);

        // 进度条
        gbc.gridx  = 0;
        gbc.gridy  = 5;
        gbc.gridwidth  = 2;
        progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true);
        progressBar.setString(" 等待开始...");
        mainPanel.add(progressBar,  gbc);

        // 处理按钮
        gbc.gridx  = 0;
        gbc.gridy  = 6;
        gbc.gridwidth  = 2;
        gbc.insets  = new Insets(15, 8, 8, 8);
        processBtn = new JButton("开始处理");
        processBtn.addActionListener(new  ProcessActionListener());
        mainPanel.add(processBtn,  gbc);

        add(mainPanel);
    }

    private class DirectoryChooser implements ActionListener {
        private JTextField textField;

        public DirectoryChooser(JTextField textField) {
            this.textField  = textField;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = chooser.showOpenDialog(ImageResizerUIWithJFIFSupport.this);
            if(returnVal == JFileChooser.APPROVE_OPTION) {
                textField.setText(chooser.getSelectedFile().getAbsolutePath());
            }
        }
    }

    private class ProcessActionListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String inputDir = inputDirField.getText();
            String outputDir = outputDirField.getText();
            int width, height;

            try {
                width = Integer.parseInt(widthField.getText());
                height = Integer.parseInt(heightField.getText());
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(ImageResizerUIWithJFIFSupport.this,
                        "请输入有效的宽度和高度值", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if(inputDir.isEmpty()  || outputDir.isEmpty())  {
                JOptionPane.showMessageDialog(ImageResizerUIWithJFIFSupport.this,
                        "请选择输入和输出目录", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            File inputDirectory = new File(inputDir);
            File outputDirectory = new File(outputDir);

            if(!inputDirectory.exists()  || !inputDirectory.isDirectory())  {
                JOptionPane.showMessageDialog(ImageResizerUIWithJFIFSupport.this,
                        "输入目录不存在或不是目录", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if(!outputDirectory.exists())  {
                if(!outputDirectory.mkdirs())  {
                    JOptionPane.showMessageDialog(ImageResizerUIWithJFIFSupport.this,
                            "无法创建输出目录", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }

            // 支持的文件格式扩展名
            String[] supportedExtensions = {".jpg", ".jpeg", ".png", ".gif", ".jfif"};

            // 获取输入目录中的所有支持格式的图片文件
            File[] files = inputDirectory.listFiles((dir,  name) -> {
                String lowerName = name.toLowerCase();
                for (String ext : supportedExtensions) {
                    if (lowerName.endsWith(ext))  {
                        return true;
                    }
                }
                return false;
            });

            if(files == null || files.length  == 0) {
                JOptionPane.showMessageDialog(ImageResizerUIWithJFIFSupport.this,
                        "输入目录中没有找到支持的图片文件", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 创建后台任务
            SwingWorker<Void, Integer> worker = new SwingWorker<Void, Integer>() {
                private int successCount = 0;
                private int failCount = 0;

                @Override
                protected Void doInBackground() throws Exception {
                    processBtn.setEnabled(false);
                    progressBar.setString(" 处理中...");
                    progressBar.setValue(0);

                    int total = files.length;
                    for (int i = 0; i < total; i++) {
                        File file = files[i];
                        try {
                            // 确定输出文件名和格式
                            String outputFileName = file.getName();
                            if (!preserveFormatCheckBox.isSelected())  {
                                // 如果不保持原始格式，统一转为JPG
                                int dotIndex = outputFileName.lastIndexOf('.');
                                if (dotIndex > 0) {
                                    outputFileName = outputFileName.substring(0,  dotIndex) + ".jpg";
                                }
                            }

                            File outputFile = new File(outputDirectory, outputFileName);
                            ImageResizerUI.resizeImage(file,  outputFile, width, height);
                            successCount++;
                        } catch (IOException ex) {
                            ex.printStackTrace();
                            failCount++;
                        }

                        // 更新进度
                        int progress = (int) (((i + 1) / (double) total) * 100);
                        publish(progress);
                    }

                    return null;
                }

                @Override
                protected void process(List<Integer> chunks) {
                    int progress = chunks.get(chunks.size()  - 1);
                    progressBar.setValue(progress);
                    progressBar.setString(String.format(" 处理中... %d%%", progress));
                }

                @Override
                protected void done() {
                    processBtn.setEnabled(true);
                    progressBar.setString(" 处理完成");

                    JOptionPane.showMessageDialog(ImageResizerUIWithJFIFSupport.this,
                            String.format(" 处理完成!\n成功: %d, 失败: %d", successCount, failCount),
                            "完成", JOptionPane.INFORMATION_MESSAGE);
                }
            };

            // 执行后台任务
            worker.execute();
        }
    }
}